﻿using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Microsoft.Coding4Fun.TweetCraft.Targa
{
    internal static class BinaryWriterExtensions
    {
        public static void WriteStruct<T>(this BinaryWriter binaryWriter, T value) where T:struct
        {
            if (binaryWriter == null)
                throw new ArgumentNullException("binaryWriter");

            // Allocate a byte array of the size of the struct
            var buffer = new byte[Marshal.SizeOf(typeof(T))];

            GCHandle? handle = null;

            try
            {
                // Pin the byte array so that GC doesn't reorganize it
                handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

                // Push the structure into the ptr of the pinned byte array
                Marshal.StructureToPtr(value, handle.Value.AddrOfPinnedObject(), false);

                // Perform the actual writing
                binaryWriter.Write(buffer);
            }
            finally
            {
                if (handle.HasValue)
                {
                    // Free the GC handle
                    handle.Value.Free();
                }
            }
        }
    }
}
